<template>
  <div>
    <transition name="el-fade-in-linear">
      <div v-show="flag" class="backtop" @click="backtop">
        <i class="top-img"></i>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  data () {
    return {
      flag: false
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll () {
      var dis =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop

      if (dis > 400) {
        this.flag = true
      } else {
        this.flag = false
      }
    },
    backtop () {
      var timer = setInterval(function () {
        const osTop =
          document.documentElement.scrollTop || document.body.scrollTop
        const ispeed = Math.floor(-osTop / 5)
        document.documentElement.scrollTop = document.body.scrollTop =
          osTop + ispeed
        this.isTop = true
        if (osTop === 0) {
          clearInterval(timer)
        }
      }, 30)
    }
  }
}
</script>

<style lang='scss' scope>
.backtop {
  width: 50px;
  height: 50px;
  //   background-color: darkkhaki;

  position: fixed;
  right: 50px;
  bottom: 100px;
  padding: 8px;
  border-radius: 10px;

  .top-img {
    display: block;
    margin: 5px 0px 0px 5px;
    width: 40px;
    height: 40px;
    background: url(~@/assets/backtop.png);
    background-size: 100%;
  }
}
.backtop:hover {
  background-color: #d6d9da;
}
</style>
